import json
from MBlog_backend.custom_response import custom_response
from django.forms.models import model_to_dict
from django.db.models import F
from MBlog_backend.decorators import login_required
from django.db.models import ObjectDoesNotExist

# 数据库模型
from .models import comment as comment_model
from user.models import user as user_model
from user.models import token as token_model
from article.models import articles as art_model


# Create your views here.

def article(request):
    body = json.loads(request.body)
    art_id = body.get('id')
    comments = comment_model.objects.filter(article_id__id=art_id).order_by('create_time')
    comments = comments.annotate(commentId=F('id'), userId=F('user__id'), nickname=F('user__nickname'),
                                 avatar=F('user__avatar'), createTime=F('create_time'), pId=F('parent__id'))
    comments = comments.values('commentId', 'content', 'createTime', 'userId', 'nickname', 'avatar',
                               'pId', 'to_user_id', 'to_user__avatar', 'to_user__nickname').order_by('id')
    comments_dict = {}
    for comment in comments:
        parent_id = comment.get('pId', None)
        comment_dict = {}
        author = {'id': comment['userId'], 'nickname': comment['nickname'], 'avatar': comment['avatar']}
        toUser = {'id': comment['to_user_id'],
                  'nickname': comment['to_user__nickname'], 'avatar': comment['to_user__avatar']}
        comment_dict.update(commentId=comment['commentId'], content=comment['content'], toUser=toUser,
                            createTime=comment['createTime'], author=author, childrens=[])
        if not parent_id:
            comments_dict[comment['commentId']] = comment_dict
        else:
            childrens = comments_dict[parent_id]['childrens']
            childrens.append(comment_dict)
    comments_list = [x for x in comments_dict.values()]
    resp = custom_response()
    resp.data_update(comments_list)
    return resp.response


@login_required
def edit(request):
    token = request.headers.get('Oauth-Token')
    body = json.loads(request.body)
    art_id = body.get('article').get('id')
    content = body.get('content')
    parent_id = ''
    parent = body.get('parent')
    if parent:
        parent_id = parent.get('id')
    to_user_id = ''
    to_user = body.get('toUser')
    if to_user:
        to_user_id = to_user.get('id')
    user = user_model.objects.filter(token__token=token).values('id', 'avatar', 'nickname').first()
    comment_obj = comment_model(content=content, article_id=art_id, user_id=user['id'])
    if parent_id:
        comment_obj.parent_id = parent_id
    if to_user_id:
        comment_obj.to_user_id = to_user_id
    resp = custom_response()
    try:
        comment_obj.save()
    except ObjectDoesNotExist:
        resp.set_code('6001')
        resp.set_message('评论失败！')
    comment_dict = {'commentId': comment_obj.id, 'content': comment_obj.content, 'parent': parent,
                    'toUser': to_user, 'createTime': comment_obj.create_time,
                    'author': user}
    art_obj = art_model.objects.get(id__exact=art_id)
    art_obj.comment_num += 1
    art_obj.save()
    resp = custom_response()
    resp.data_update(comment_dict)
    return resp.response
